package com.example.todolist.view

import android.Manifest
import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.TextView
import android.widget.Toast
import androidx.activity.viewModels
import androidx.annotation.RequiresPermission
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.example.todolist.R
import com.example.todolist.commen.TodoCategoryEnum
import com.example.todolist.commen.TodoImportance
import com.example.todolist.commen.TodoStatus
import com.example.todolist.database.model.TodoEntity
import com.example.todolist.databinding.ActivityTodoDetailBinding
import com.example.todolist.util.AlarmUtils
import com.example.todolist.util.LoggerTag
import com.example.todolist.util.LoggerTag.Companion.MAIN_TAG
import com.example.todolist.viewmodel.TodoListViewModel
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

@AndroidEntryPoint
class TodoDetailActivity : AppCompatActivity() {
    val DEFAULT_TODOID = -1
    private lateinit var binding: ActivityTodoDetailBinding
    private lateinit var timeButton: Button
    private lateinit var saveButton: Button
    private lateinit var tvTitle: TextView
    private lateinit var tvPerson: TextView
    private lateinit var rgImportance: RadioGroup
    private lateinit var tvDetail: TextView

    private var selCategoryId: Int = -1
    private var todoId: Int = -1
    private val viewModel: TodoListViewModel by viewModels()
    private var selectedDateTime: String = ""
    private var currentTodo: TodoEntity = TodoEntity()

    override fun onCreate(savedInstanceState: Bundle?) {
        lifecycleScope.launch {
            super.onCreate(savedInstanceState)
            binding = ActivityTodoDetailBinding.inflate(layoutInflater)
            setContentView(binding.root)
            // 获取主页面点击的分类
            selCategoryId = intent.getIntExtra("selCategoryId", TodoCategoryEnum.UNCATEGORY.code)
            todoId = intent.getIntExtra("todoId", DEFAULT_TODOID)
            Log.d(LoggerTag.MAIN_CATEGORY, "onCreate: 拿到cateId$selCategoryId")
            init()

            timeButton.setOnClickListener {
                showTimePickerDialog(it)
            }
            // 进行保存或者更新
            saveButton.setOnClickListener {
                lifecycleScope.launch {
                    addOrUpdateTodoEntity()
                }
            }
            binding.backButton.setOnClickListener {
                finish()
            }
        }
    }

    private suspend fun init() {
        timeButton = binding.ddlTime
        saveButton = binding.btnSave
        rgImportance = binding.rgPriority
        tvTitle = binding.todoTitle
        tvPerson = binding.person
        tvDetail = binding.todoDescription
        if (todoId != -1) {
            currentTodo = viewModel.getTodoById(todoId)
            currentTodo.apply {
                timeButton.text = if (isExpired) {
                    "$endTime:已过期"
                } else {
                    endTime
                }
                tvTitle.text = title
                tvDetail.text = detail
                tvPerson.text = username
                selectedDateTime = endTime
                val radioButtonId = when (importance) {
                    TodoImportance.HIGH.code -> R.id.rb_high
                    TodoImportance.MIDDLE.code -> R.id.rb_medium
                    TodoImportance.LOW.code -> R.id.rb_low
                    else -> -1
                }
                if (radioButtonId != -1) {
                    rgImportance.check(radioButtonId)  // 设置选中状态
                }

            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun showTimePickerDialog(view: View) {
        // 获取当前日期和时间
        val calendar = Calendar.getInstance()
        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH)
        val day = calendar.get(Calendar.DAY_OF_MONTH)
        val hour = calendar.get(Calendar.HOUR_OF_DAY)
        val minute = calendar.get(Calendar.MINUTE)

        // 先显示日期选择器
        val datePickerDialog = DatePickerDialog(
            this, { _, selectedYear, selectedMonth, selectedDay ->
                // 当日期选择完成后，显示时间选择器
                val timePickerDialog = TimePickerDialog(
                    this, { _, selectedHour, selectedMinute ->
                        // 当时间选择完成后，更新按钮的文本
                        selectedDateTime =
                            "$selectedYear-${selectedMonth + 1}-${selectedDay} $selectedHour:$selectedMinute"
                        timeButton.text = selectedDateTime

                        currentTodo.isExpired = false
                        currentTodo.endTime = selectedDateTime
                        if (compareTime(selectedDateTime)) {
                            // 过期就不发送提醒弹窗了
                            timeButton.text = "${timeButton.text}:已过期"
                            currentTodo.isExpired = true
                        }
                    }, hour, minute, true
                )
                timePickerDialog.show()
            }, year, month, day
        )
        datePickerDialog.show()
    }

    private suspend fun addOrUpdateTodoEntity() {
        if (tvTitle.text.isEmpty() || tvDetail.text.isEmpty() || tvPerson.text.isEmpty() || selectedDateTime.isEmpty()) {
            Toast.makeText(this, "请将信息填写完整！", Toast.LENGTH_SHORT).show()
            return
        }
        val checkedId = rgImportance.checkedRadioButtonId
        var todoImportance: Int = -1
        if (checkedId != -1) {
            val selectedRadioButton = rgImportance.findViewById<RadioButton>(checkedId)
            val tagValue = selectedRadioButton.tag.toString()  // 获取 tag 值
            todoImportance = tagValue.toIntOrNull() ?: 0
        }
        if (todoId != DEFAULT_TODOID) {
            // 更新
            currentTodo.apply {
                title = tvTitle.text.toString()
                username = tvPerson.text.toString()
                importance = todoImportance
                detail = tvDetail.text.toString()
            }

            viewModel.updateTodo(currentTodo)
        } else {
            currentTodo.apply {
                title = tvTitle.text.toString()
                username = tvPerson.text.toString()
                importance = todoImportance
                detail = tvDetail.text.toString()
                orderNum = getOrderNum()
                // 如果点击“全部”进来的应该是0==>-1
                // kotlin煤油三元运算符
                categoryId =
                    if (selCategoryId != TodoCategoryEnum.CATEGORY_ALL.code) {
                        selCategoryId
                    } else {
                        TodoCategoryEnum.UNCATEGORY.code
                    }
            }

            viewModel.insertTodo(currentTodo)
        }
        finish()
    }

    // 判断传入时间是否在现在时间之前
    private fun compareTime(selectedTimeStr: String): Boolean {
        // 1. 定义时间格式（需与传入的字符串格式一致）
        val format = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA)

        try {
            // 2. 解析时间字符串为 Date 对象
            val selectedDate = format.parse(selectedTimeStr) ?: return false // 解析失败返回 false

            // 3. 获取当前时间
            val currentDate = Date()

            // 4. 比较时间：selectedDate 是否早于当前时间？
            return selectedDate.before(currentDate)
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "时间解析异常", Toast.LENGTH_SHORT).show()
            return false // 解析异常时返回 false
        }
    }

    // 如果是新添加的需要获取orderNum==>根据get数组Count
    private suspend fun getOrderNum(): Int {
        return viewModel.getMaxOrder() + 1
    }
}
